use std::{backtrace::Backtrace, sync::Arc};

use crate::{exception::ErrorCodeBacktrace, ErrorCode};

#[derive(thiserror::Error)]
enum OtherErrors {
    AnyHow { error: anyhow::Error },
}

impl std::fmt::Display for OtherErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OtherErrors::AnyHow { error } => write!(f, "{}", error),
        }
    }
}

impl std::fmt::Debug for OtherErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OtherErrors::AnyHow { error } => write!(f, "{:?}", error),
        }
    }
}

impl From<anyhow::Error> for ErrorCode {
    fn from(error: anyhow::Error) -> Self {
        ErrorCode::create(
            1001,
            format!("{}, source: {:?}", error, error.source()),
            Some(Box::new(OtherErrors::AnyHow { error })),
            Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::capture()))),
        )
    }
}

impl From<std::net::AddrParseError> for ErrorCode {
    fn from(error: std::net::AddrParseError) -> Self {
        ErrorCode::BadAddressFormat(format!("Bad address format, cause: {}", error))
    }
}

impl From<libloading::Error> for ErrorCode {
    fn from(error: libloading::Error) -> Self {
        ErrorCode::DylibLoadFailed(format!("Dylib failed load, cause: {}", error))
    }
}

impl From<sqlx::Error> for ErrorCode {
    fn from(error: sqlx::Error) -> Self {
        ErrorCode::DbInnerError(format!("Database error, cause: {}", error))
    }
}

impl From<serde_json::Error> for ErrorCode {
    fn from(error: serde_json::Error) -> Self {
        ErrorCode::from_std_error(error)
    }
}

impl From<std::io::Error> for ErrorCode {
    fn from(error: std::io::Error) -> Self {
        ErrorCode::from_std_error(error)
    }
}

impl From<tonic::transport::Error> for ErrorCode {
    fn from(error: tonic::transport::Error) -> Self {
        ErrorCode::from_std_error(error)
    }
}

impl From<tonic::Status> for ErrorCode {
    fn from(error: tonic::Status) -> Self {
        ErrorCode::RemoteInvokerError(error.message())
    }
}

impl From<Box<bincode::ErrorKind>> for ErrorCode {
    fn from(error: Box<bincode::ErrorKind>) -> Self {
        ErrorCode::from_std_error(error)
    }
}

impl From<toml::de::Error> for ErrorCode {
    fn from(error: toml::de::Error) -> Self {
        ErrorCode::from_std_error(error)
    }
}
